'use client'

import { useState } from 'react'
import { ArrowDownIcon } from '@heroicons/react/24/outline'
import * as XLSX from 'xlsx'
import { SerializedFinanceRecord } from "@/types"

interface ReportsHeaderProps {
  incomeRecords: SerializedFinanceRecord[]
  expenseRecords: SerializedFinanceRecord[]
}

export function ReportsHeader({ incomeRecords, expenseRecords }: ReportsHeaderProps) {
  const handleExport = () => {
    const incomeData = incomeRecords.map(record => ({
      '收入金额': record.amount,
      '收入说明': record.description,
      '记录时间': new Date(record.createdAt).toLocaleString(),
    }));

    const expenseData = expenseRecords.map(record => ({
      '支出金额': record.amount,
      '支出说明': record.description,
      '记录时间': new Date(record.createdAt).toLocaleString(),
    }));

    const worksheet = XLSX.utils.json_to_sheet([...incomeData, ...expenseData]);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '财务报表');

    // 设置列样式
    const range = XLSX.utils.decode_range(worksheet['!ref']!);
    for (let row = range.s.r; row <= range.e.r; row++) {
      for (let col = range.s.c; col <= range.e.c; col++) {
        const cell = worksheet[XLSX.utils.encode_cell({ r: row, c: col })];
        if (cell) { // 确保 cell 存在
          if (row === 0) {
            // 设置表头背景颜色
            cell.s = {
              fill: {
                fgColor: { rgb: "FFDDDD" } // 浅红色
              }
            };
          } else if (col === 0 || col === 1) {
            // 设置收入金额和说明的背景颜色
            cell.s = {
              fill: {
                fgColor: { rgb: "CCFFCC" } // 浅绿色
              }
            };
          } else if (col === 2) {
            // 设置记录时间的背景颜色
            cell.s = {
              fill: {
                fgColor: { rgb: "CCCCFF" } // 浅蓝色
              }
            };
          }
        }
      }
    }

    // 导出 Excel 文件
    XLSX.writeFile(workbook, '财务报表.xlsx');
  }

  return (
    <div className="flex justify-between items-center">
      <h1 className="text-2xl font-semibold text-gray-900">财务报表</h1>
      <div className="flex items-center">
        <button
          onClick={handleExport}
          className="bg-green-500 text-white px-4 py-2 rounded-md hover:bg-green-600 flex items-center"
        >
          <ArrowDownIcon className="h-5 w-5 mr-2" />
          导出报表
        </button>
      </div>
    </div>
  )
} 